<template>
    <div>
        <!--  顶部面包屑  -->
        <div class="ccui-navigation">
            <!-- 面包屑 -->
            <breadcrumb
                :breadcrumbArr="breadcrumbArr"
                :breadcrumbLastItem="breadcrumbLastItem"
                :state="$route.query.id ? 'edit' : 'create'"
                @handleBack="handleBack"
            />
        </div>
        <div v-if="isTrue" class="ccui-app-container-detail">
            <div class="ccui-app-container-detail-body">
                <el-tabs v-model="activeName" class="el-tabs__customize">
                    <el-tab-pane label="基本信息" name="a">
                        <basicInfo ref="basicInfo" @getSettlementList="getSettlementList" :form="writeOffForm"/>
                    </el-tab-pane>
                    
                    <el-tab-pane label="结算单明细" name="b">
                        <div class="ccui-multifunctional-table-wrapper">
                            <el-table
                                :data="showTableData"
                                max-height="525"
                                ref="tableList"
                                border
                                :summary-method="getSummaries"
                                show-summary
                            >
                                <el-table-column
                                    v-for="(item, i) in tableColumnList"
                                    :label="item.label"
                                    :fixed="item.fixed"
                                    :type="item.type"
                                    :prop="item.prop"
                                    :header-align="item.headerAlign || 'left'"
                                    :align="item.align"
                                    :min-width="item.width"
                                    :key="i"
                                    :show-overflow-tooltip="true"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                    
                    <el-tab-pane label="验收单明细" name="c">
                        <div class="ccui-multifunctional-table-wrapper">
                            <el-table
                                :data="showTableData1"
                                max-height="525"
                                ref="tableList"
                                border
                                :summary-method="getSummaries1"
                                show-summary
                            >
                                <el-table-column
                                    v-for="(item, i) in tableColumnList1"
                                    :label="item.label"
                                    :fixed="item.fixed"
                                    :type="item.type"
                                    :prop="item.prop"
                                    :header-align="item.headerAlign || 'left'"
                                    :align="item.align"
                                    :min-width="item.width"
                                    :key="i"
                                    :show-overflow-tooltip="true"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                    
                    <el-tab-pane label="附件" name="d" v-if="isTrue" class="file-group">
                        <fileInfo ref="fileInfo" v-model="fileList"/>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <!--  按钮  -->
        <el-bottom-guide>
            <ul class="ccui-bottom-button">
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save"
                        @click="submitHandle(0)"
                    >保存并校验
                    </el-button>
                </li>
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save"
                        @click="submitHandle(1)"
                    >保存并提交
                    </el-button>
                </li>
                <div class="ccui-bottom-guide-divider"/>
                <li>
                    <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
                    >返回
                    </el-button>
                </li>
            </ul>
        </el-bottom-guide>
    </div>
</template>

<script>
import breadcrumb from "@/basa/components/public/breadcrumb";
import basicInfo from "@/app/settlement-management/equipment/eq_writeOff/views/components/basicInfo";
import fileInfo from "@/basa/components/public/uploadInfo2";
import BigNumber from "bignumber.js";
import {
    saveSettlementWrite,
    editSettlementWrite,
    getSettlementWriteById
} from "@/app/settlement-management/equipment/api";
import {dateFormat1} from "@/basa/utils";

export default {
    name: "item_add",
    components: {breadcrumb, basicInfo, fileInfo},
    data() {
        return {
            saveSettlementWrite,
            editSettlementWrite,
            isTrue: false,
            breadcrumbLastItem: "",
            // 面包屑导航
            breadcrumbArr: [
                {
                    path: "/settlement-management/settlement-maintenance-approval/settlement-maintenance-all",
                    text: "结算管理"
                },
                {
                    path: "/settlement-management/equipment-preserve/ListAll",
                    text: "设备采购结算管理"
                },
                {
                    path: "/settlement-management/equipment-writeOff/ListAll",
                    text: "结算单冲销"
                }
            ],
            writeOffForm: {
                writeoffReason: "",
                reportInOrgName: "",
                reportInOrgId: null,
                writeoffCode: "",
                writeoffName: "",
                reversal: [],
                settlementCode: "",
                settlementName: "",
                contractCode: "",
                contractId: null,
                contractName: "",
                supplierId: null,
                supplierName: "",
                supplierCode: "111",
                contractMoney: "",
                writeoffMoney: "",
                writeoffCount: "",
                reportUsername: "",
                reportTime: dateFormat1(new Date()),
                remarks: "",
                writeoffStart: "",
                writeoffEnd: "",
                version: 0
            },
            activeName: "a",
            settlementList: [],
            fileList: [],
            showTableData: [],
            showTableData1: [],
            tableColumnList: [
                {
                    type: "index",
                    label: "序号",
                    fixed: "left",
                    width: "55"
                },
                {
                    label: "设备物资编码",
                    prop: "materialCode",
                    width: "110"
                },
                {
                    label: "验收单编号",
                    prop: "acceptCode",
                    width: "130"
                },
                {
                    label: "设备物资名称",
                    prop: "materialName",
                    width: "300"
                },
                {
                    label: "设备型号说明",
                    prop: "materialState",
                    width: "130"
                },
                {
                    label: "计量单位",
                    prop: "measureUnit",
                    width: "100"
                },
                {
                    label: "验收日期",
                    prop: "acceptTime",
                    width: "100"
                },
                {
                    label: "剩余可结算数量",
                    prop: "unTransportCount",
                    width: "130"
                },
                {
                    label: "冲销数量",
                    prop: "settlementCount",
                    width: "100"
                },
                // {
                //     label: "税率",
                //     prop: "taxRatePercent"
                // },
                
                {
                    label: "含税单价",
                    prop: "unitPriceWithTax",
                    width: "130"
                },
                {
                    label: "冲销金额",
                    prop: "moneyWithTax",
                    width: "130"
                },
                // {
                //     label: "不含税单价",
                //     prop: "unitPriceWithoutTax",
                //     width: "150",
                //     align: "right"
                // },
                // {
                //     label: "不含税金额",
                //     prop: "moneyWithoutTax",
                //     width: "150",
                //     align: "right"
                // },
                {
                    label: "生产厂家/品牌",
                    prop: "brand",
                    width: "130"
                }
            ],
            tableColumnList1: [
                {
                    type: "index",
                    label: "序号",
                    fixed: "left",
                    width: "55"
                },
                {
                    label: "验收单编号",
                    prop: "acceptCode",
                    width: "155"
                },
                {
                    label: "验收单名称",
                    prop: "acceptName",
                    width: "200"
                },
                {
                    label: "验收日期",
                    prop: "acceptTime",
                    width: "100"
                },
                {
                    label: "验收人",
                    prop: "acceptor"
                },
                {
                    label: "设备物资名称",
                    prop: "materialName",
                    width: "300"
                },
                {
                    label: "设备型号说明",
                    prop: "materialState",
                    width: "130"
                },
                {
                    label: "计量单位",
                    prop: "measureUnit"
                },
                {
                    label: "合同编号",
                    prop: "contractCode",
                    width: "150"
                },
                {
                    label: "验收数量",
                    prop: "acceptCount",
                    width: "80"
                },
                // {
                //     label: "本次结算数量",
                //     prop: "settlementCount",
                //     width: "130"
                // },
                // {
                //     label: "实际验收数量",
                //     prop: "acceptCount",
                //     width: "130"
                // },
                {
                    label: "结算单价",
                    prop: "unitPriceWithTax",
                    width: "130",
                    align: "right"
                }
                // {
                //     label: "生产厂家/品牌",
                //     prop: "brand",
                //     width: "130"
                // },
                // {
                //     label: "备注",
                //     prop: "remarks",
                //     width: "100"
                // }
            ],
        }
    },
    methods: {
        submitHandle(status) {
            this.$refs["basicInfo"].handleSubmit().then(form => {
                form.writeoffStart = form.reversal[0];
                form.writeoffEnd = form.reversal[1];
                let fileList = JSON.parse(JSON.stringify(this.fileList))
                fileList.forEach((e, i) => {
                    e.sn = i;
                    e.fileInfoId = e.uploadId;
                    e.uploadTime = e.createTime || e.uploadTime;
                });
                let params = {
                    settlementWriteOffBO: form,
                    uploadIds: fileList,
                    operType: status
                };
                this.$route.query.id ? this.handleSubmitCommit(params, editSettlementWrite) : this.handleSubmitCommit(params, saveSettlementWrite);
            }).catch(e => {
                console.log('catch', e);
                // this.activeName = e;
            })
        },
        handleSubmitCommit(params, callBack) {
            callBack(params).then(res => {
                this.$message({
                    message: res.data.message,
                    type: "success",
                    showClose: true,
                    ccuiCustom: true,
                    duration: 2000
                });
                this.handleBack();
            }).catch(e => {
                console.log(e);
            });
        },
        getSettlementList(data) {
            this.settlementList = data;
            this.handleTable(data);
            this.showTableData1 = data.filter(e => e.isMainInventory == 0 && e.isOtherCost == 0 && !e.isCategories && e.acceptCode);
        },
        getDetail() {
            getSettlementWriteById({id: this.$route.query.id, isShowPageLoading: true}).then(res => {
                let result = res.data.data;
                delete result.settlementWriteOffBO.createTime;
                this.writeOffForm = result.settlementWriteOffBO;
                this.writeOffForm.reversal = [result.settlementWriteOffBO.writeoffStart, result.settlementWriteOffBO.writeoffEnd];
                this.fileList = result.writeOffFiles;
                this.getSettlementList(result.settlementBOList);
                this.isTrue = true;
            });
        },
        handleTable(data) {
            if (data.length) {
                let yunshu = [], // 运输类
                    hebingqian = [], // 没有合并的数据
                    hebinghou = [], // 合并后隐藏的数据
                    hebingMerge = [], // 合并后生成的数据
                    qita = []; // 其他类数据
                data.map(e => {
                    if (e.isCategories && e.isCategories == 1) {
                        yunshu.push(e);
                    } else if (e.isMerge == 0 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebingqian.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebinghou.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 1 && e.isOtherCost == 0) {
                        hebingMerge.push(e);
                    } else if (e.isOtherCost && e.isOtherCost == 1) {
                        qita.push(e);
                    }
                });
                this.showTableData = [...hebingqian, ...hebingMerge, ...yunshu, ...qita];
            } else {
                this.showTableData = [];
            }
        },
        handleBack() {
            this.$router.push("/settlement-management/equipment-writeOff/ListAll");
        },
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            if (
                                column.label == "验收数量" ||
                                column.label == "冲销数量" ||
                                column.label == "冲销金额"
                            ) {
                                let num = new BigNumber(Number(prev)).plus(Number(curr)).toNumber();
                                return Number(num)
                            }
                        } else {
                            return prev;
                        }
                    }, 0);
                    if (column.label == "验收数量") {
                        sums[index] = Number(sums[index]).toFixed(3);
                    }
                    if (column.label == "冲销数量") {
                        sums[index] = Number(sums[index]).toFixed(3);
                    }
                    
                    if (column.label == "冲销金额") {
                        sums[index] = Number(sums[index]).toFixed(2);
                    }
                } else {
                    sums[index] = "";
                }
            });
            return sums;
        },
        getSummaries1(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            if (column.label == "订单数量" || column.label == "验收数量") {
                                let num = new BigNumber(Number(prev)).plus(Number(curr)).toNumber();
                                return Number(num)
                            }
                        } else {
                            return (prev = " ");
                        }
                    }, 0);
                    if (column.label == "订单数量") {
                        sums[index] = Number(sums[index]).toFixed(3);
                    }
                    if (column.label == "验收数量") {
                        sums[index] = Number(sums[index]).toFixed(3);
                    }
                } else {
                    sums[index] = "";
                }
            });
            return sums;
        },
    },
    beforeRouteLeave(to, from, next) {
        this.isTrue = false;
        this.activeName = "a";
        next();
    },
    activated() {
        this.$route.query.id ? this.getDetail() : this.isTrue = true;
    }
}
</script>

<style scoped lang="scss">
/deep/ .ccui-multifunctional-table-wrapper {
    margin-top: 40px;
}

/deep/ .el-group-title.ccui-group-wrapper .extend-btn {
    top: 0;
}

/deep/ .el-tabs__customize {
    padding-bottom: 50px;
}
</style>